package com.jinzecloud.reportapproval.controller;

import java.io.IOException;
import java.util.Arrays;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jinzecloud.reportapproval.bean.SampleDetails;
import com.jinzecloud.reportapproval.bean.SampleInspection;
import com.jinzecloud.reportapproval.bean.SampleSheet;
import com.jinzecloud.reportapproval.bean.SampleSheetWorkplaceDetail;
import com.jinzecloud.reportapproval.dto.AuditParam;
import com.jinzecloud.reportapproval.dto.DataStagingParam;
import com.jinzecloud.reportapproval.enums.StateEnum;
import com.jinzecloud.reportapproval.service.*;
import com.jinzecloud.reportapproval.vo.SampleSheetVo;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import com.jinzecloud.reportapproval.service.SampleSheetService;
import com.jinzecloud.reportapproval.utils.R;

import javax.servlet.http.HttpServletRequest;


/**
 * 验样/抽样单
 *
 * @author æ­å°
 * @email 1971240051@qq.com
 * @date 2024-12-03 16:18:45
 */
@RestController
@RequestMapping("/sampleSheet")
@RequiredArgsConstructor
public class SampleSheetController {
    
    private final SampleSheetService sampleSheetService;
    private final SampleDetailsService sampleDetailsService;
    private final SampleSheetWorkplaceDetailService sampleSheetWorkplaceDetailService;
    private final AdminService adminService;
    private final SampleInspectionService sampleInspectionService;

    @PostMapping
    @Transactional(rollbackFor = Exception.class)
    public R save(@RequestBody SampleSheetVo sampleSheetVo) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        SampleSheet sampleSheet = new SampleSheet();
        BeanUtils.copyProperties(sampleSheetVo, sampleSheet);
        sampleSheet.setState(StateEnum.UN_SUBMIT.getState()).setWordPath("").setPdfPath("");
        sampleSheet.setCreatedUserId(adminService.getIdByName(authentication.getName()));
        R r = sampleSheetService.saveSampleSheet(sampleSheet);
        if (CollectionUtil.isNotEmpty(sampleSheet.getSampleDetailsList())) {
            sampleSheet.getSampleDetailsList().forEach(item -> item.setSampleSheetId(sampleSheet.getId()));
            sampleDetailsService.saveBatch(sampleSheet.getSampleDetailsList());
        }
        if (CollectionUtil.isNotEmpty(sampleSheet.getSampleSheetWorkplaceDetailList())) {
            sampleSheet.getSampleSheetWorkplaceDetailList().forEach(item -> item.setSampleSheetId(sampleSheet.getId()));
            sampleSheetWorkplaceDetailService.saveBatch(sampleSheet.getSampleSheetWorkplaceDetailList());
        }
        if (sampleSheetVo.getCoversList() != null){
            for (SampleDetails sampleDetails : sampleSheetVo.getCoversList()) {
                SampleInspection sampleInspection = new SampleInspection().setState(-1);
                BeanUtils.copyProperties(sampleSheetVo, sampleInspection);
                sampleInspection.setSampleNumber(sampleDetails.getSampleSupplied());
                sampleInspectionService.save(sampleInspection);
                if (sampleDetails != null) {
                    SampleDetails sampleDetails1 = new SampleDetails();
                    sampleDetails1.setSampleInspectionId(sampleInspection.getId());
                    sampleDetails1.setAppearanceNumber(sampleDetails.getAppearanceNumber());
                    sampleDetails1.setSampleNumber(sampleDetails.getSampleNumber());
                    sampleDetails1.setAppearanceDate(sampleDetails.getAppearanceDate());
                    sampleDetails1.setPurpose(sampleDetails.getPurpose());
                    sampleDetailsService.save(sampleDetails1);
                }
                if (CollectionUtil.isNotEmpty(sampleInspection.getSampleInspectionWorkplaceDetailList())) {
                    SampleSheetWorkplaceDetail sampleSheetWorkplaceDetail = new SampleSheetWorkplaceDetail();
                    sampleSheetWorkplaceDetail.setSampleInspectionId(sampleInspection.getId());
                    sampleSheetWorkplaceDetail.setColumnName(sampleInspection.getSampleType());
                    sampleSheetWorkplaceDetail.setUnitName(sampleInspection.getSampleType());
                    sampleSheetWorkplaceDetail.setPostalCode(sampleInspection.getSampleType());
                    sampleSheetWorkplaceDetail.setPhone(sampleInspection.getSampleType());
                    sampleSheetWorkplaceDetailService.save(sampleSheetWorkplaceDetail);
                }
            }
        }
        return R.ok();
    }

    @PutMapping
    public R update(@RequestBody SampleSheet sampleSheet) {
        sampleSheet.setState(StateEnum.UN_SUBMIT.getState()).setWordPath("").setPdfPath("");
        sampleSheetService.updateById(sampleSheet);
        if (CollectionUtil.isNotEmpty(sampleSheet.getSampleDetailsList())) {
            sampleDetailsService.remove(new LambdaQueryWrapper<SampleDetails>().eq(SampleDetails::getSampleSheetId, sampleSheet.getId()));
            sampleSheet.getSampleDetailsList().forEach(item -> item.setSampleSheetId(sampleSheet.getId()));
            sampleDetailsService.saveBatch(sampleSheet.getSampleDetailsList());
        }
        if (CollectionUtil.isNotEmpty(sampleSheet.getSampleSheetWorkplaceDetailList())) {
            sampleSheetWorkplaceDetailService.remove(new LambdaQueryWrapper<SampleSheetWorkplaceDetail>().eq(SampleSheetWorkplaceDetail::getSampleSheetId, sampleSheet.getId()));
            sampleSheet.getSampleSheetWorkplaceDetailList().forEach(item -> item.setSampleSheetId(sampleSheet.getId()));
            sampleSheetWorkplaceDetailService.saveBatch(sampleSheet.getSampleSheetWorkplaceDetailList());
        }
        return R.ok();
    }

    @PostMapping("/review")
    public R review(@RequestBody SampleSheet sampleSheet) {
        sampleSheetService.updateById(new SampleSheet().setId(sampleSheet.getId()).setState(0));
        return R.ok();
    }

    @PostMapping("/audit")
    public R audit(@RequestBody AuditParam auditParam) {
        return sampleSheetService.audit(auditParam);
    }

    @PostMapping("/list")
    public R list(@RequestBody DataStagingParam param) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LambdaQueryWrapper<SampleSheet> sampleSheetLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sampleSheetLambdaQueryWrapper.and(w -> w.ne(SampleSheet::getState, StateEnum.APPROVAL_PASS.getState()).eq(SampleSheet::getCreatedUserId, adminService.getIdByName(authentication.getName())
        ).or().eq(SampleSheet::getState, StateEnum.APPROVAL_PASS.getState()));
        if (StrUtil.isNotEmpty(param.getSearchKey())){
            sampleSheetLambdaQueryWrapper.and(w -> w.like(StrUtil.isNotEmpty(param.getSearchKey()), SampleSheet::getProjectCode, param.getSearchKey())
                    .or().like(StrUtil.isNotEmpty(param.getSearchKey()), SampleSheet::getPrototypeTrademark, param.getSearchKey()));
        }
        Page<SampleSheet> page = sampleSheetService.page(new Page<>(param.getPageNo(), param.getPageSize()),
                sampleSheetLambdaQueryWrapper
        );
        return R.ok().setData(page);
    }

    @PostMapping("/auditList")
    public R auditList(@RequestBody DataStagingParam param) {
        return R.ok().setData(sampleSheetService.auditList(param));
    }

    @GetMapping("/{id}")
    public R getById(@PathVariable Long id) {
        return R.ok().setData(sampleSheetService.getById(id)
                .setSampleDetailsList(sampleDetailsService.list(new LambdaQueryWrapper<SampleDetails>().eq(SampleDetails::getSampleSheetId, id)))
                .setSampleSheetWorkplaceDetailList(sampleSheetWorkplaceDetailService.list(new LambdaQueryWrapper<SampleSheetWorkplaceDetail>().eq(SampleSheetWorkplaceDetail::getSampleSheetId, id)))
        );
    }

    @GetMapping("/getByProjectCode/{projectCode}")
    public R getByProjectCode(@PathVariable String projectCode) {
        SampleSheet sampleSheet = sampleSheetService.getOne(new LambdaQueryWrapper<SampleSheet>().eq(SampleSheet::getProjectCode, projectCode));
        Integer id = sampleSheet != null ? sampleSheet.getId() : null;
        return R.ok().setData(id == null ? null : sampleSheetService.getById(id)
                .setSampleDetailsList(sampleDetailsService.list(new LambdaQueryWrapper<SampleDetails>().eq(SampleDetails::getSampleSheetId, id)))
                .setSampleSheetWorkplaceDetailList(sampleSheetWorkplaceDetailService.list(new LambdaQueryWrapper<SampleSheetWorkplaceDetail>().eq(SampleSheetWorkplaceDetail::getSampleSheetId, id)))
        );
    }

    @DeleteMapping("/{id}")
    public R delete(@PathVariable Long id) {
        sampleSheetService.removeById(id);
        return R.ok();
    }

    @PostMapping("/batchDelete")
    public R batchDelete(@RequestBody Long[] ids) {
        sampleSheetService.removeByIds(Arrays.asList(ids));
        return R.ok();
    }

    @GetMapping("/getFilePath/{id}")
    public R getReportFilePath(@PathVariable("id") String id, HttpServletRequest request) throws IOException, IllegalAccessException {
        String path = sampleSheetService.getReportFilePath(id, request);
        return R.ok().put("path", path);
    }

    @RequestMapping("/viewPdf/{id}")
    public String viewPdf(@PathVariable("id") Integer id) {
        return sampleSheetService.viewPdf(id);
    }

    @RequestMapping("/viewWord/{id}")
    public String viewWord(@PathVariable("id") Integer id) {
        return sampleSheetService.viewWord(id);
    }


}
